<?php
/**
 * Created by PhpStorm.
 * User: 4399
 * Date: 2017/9/11
 * Time: 16:34
 */
namespace app\admin\controller;
use think\Request;
use \think\Session;
use \think\Cookie;
use \think\Cache;
use \user\Auth;
use think\Controller;

class Menu extends Controller
{

    protected $beforeActionList = [
        'first' => ['except' => 'getMenu'],
    ];

    protected function first()
    {
        Cookie::init(['prefix'=>'admin_','path'=>'/','httponly'=>true]);
        $token = Cookie::get('token');
        $request = Request::instance();
        $check_res = Auth::check($token,true,Session::get('id'),$request->controller(),$request->action());
        if($check_res['resCode'] == -8){
            Session::delete('id');
            Session::delete('username');
            Session::delete('username_dsp');
            Cookie::delete('token');
            format(-999,$check_res['msg']);
        }else if ($check_res['resCode'] != 2){
            format(-2,$check_res['msg']);
        }
    }

    public function detail(){
        $request = Request::instance();
        $id = $request->post('id');
        $id = intval($id);
        $MenuModel = model('Menu');
        $parent = $MenuModel->where('pid','=',0)->where('id','<>',$id)->select();
        if ($id > 0) {
            $result = $MenuModel->where('id',$id)->find();
            if ($result) {
                $ret = array(
                    'detail'=>$result,
                    'parent'=>$parent
                );
                format(0, 'success', $ret);
            } else {
                format(-2, 'fail');
            }
        } else {
            $ret = array(
                'parent'=>$parent
            );
            format(0, 'success', $ret);
        }
    }

    public function save(){
        $request = Request::instance();
        $data['pid'] = $request->post('pid','', 'SAFE_REPLACE,REMOVE_XSS');
        $data['icon'] = $request->post('icon','', 'SAFE_REPLACE,REMOVE_XSS');
        $data['url'] = $request->post('url','', 'SAFE_REPLACE,REMOVE_XSS');
        $data['title'] = $request->post('title','', 'SAFE_REPLACE,REMOVE_XSS');
        $data['order'] = $request->post('order','', 'SAFE_REPLACE,REMOVE_XSS');
        if ($request->has('status')) {
            $data['status'] = $request->post('status');
        }

        if (!empty($data['status']) && $data['status'] == true) {
            $data['status'] = 1;
        } else {
            $data['status'] = 2;
        }

        if(empty($data['title'])){
            format(-2, "请输入菜单名称");
        }

        if(empty($data['pid'])){
            $data['pid'] = 0;
        }

        if(empty($data['order']) || !is_numeric($data['order'])){
            $data['order'] = 0;
        }

        $MenuModel = model('Menu');
        $data['create_time'] = time();
        $data['update_time'] = time();
        $res = $MenuModel->data($data)->save();

        if($res){
            format(0, "添加成功!");
        }else{
            format(-2, "保存失败，请稍后再试!");
        }

    }

    public function edit(){
        $request = Request::instance();
        $id = $request->post('id',0);
        $data['pid'] = $request->post('pid','', 'SAFE_REPLACE,REMOVE_XSS');
        $data['icon'] = $request->post('icon','', 'SAFE_REPLACE,REMOVE_XSS');
        $data['url'] = $request->post('url','', 'SAFE_REPLACE,REMOVE_XSS');
        $data['title'] = $request->post('title','', 'SAFE_REPLACE,REMOVE_XSS');
        $data['order'] = $request->post('order','', 'SAFE_REPLACE,REMOVE_XSS');
        if ($request->has('status')) {
            $data['status'] = $request->post('status');
        }

        if (!empty($data['status']) && $data['status'] == true) {
            $data['status'] = 1;
        } else {
            $data['status'] = 2;
        }
        $id = intval($id);

        if($id<=0){
            format(-2, "该菜单不存在");
        }

        if(empty($data['title'])){
            format(-2, "请输入菜单名称");
        }

        if(empty($data['pid'])){
            $data['pid'] = 0;
        }

        if(empty($data['order']) || !is_numeric($data['order'])){
            $data['order'] = 0;
        }

        $MenuModel = model('Menu');
        $result = $MenuModel->where('id',$id)->find();
        $data['update_time'] = time();
        if($result) {
            $res = $MenuModel->save($data,['id' => $result['id']]);
        }else{
            format(-2, "该菜单不存在");
        }

        if($res){
            format(0, "保存成功!");
        }else{
            format(-2, "保存失败，请稍后再试!");
        }

    }

    public function mList()
    {
        $request = Request::instance();
        $page = $request->post('page');
        $pageSize = $request->post('ps');
        $sort = $request->post('sort', '', 'SAFE_REPLACE,REMOVE_XSS');
        $title = $request->post('title', '', 'SAFE_REPLACE,REMOVE_XSS');

        $page = intval($page);
        $pageSize = intval($pageSize);

        if (empty($page)) {
            $page = 1;
        }

        if (empty($pageSize)) {
            $pageSize = 15;
        }

        switch ($sort) {
            case 'id_desc' :
                $order = array('id', 'desc');
                break;
            case 'id_asc' :
                $order = array('id', 'asc');
                break;
            case 'status_desc' :
                $order = array('status', 'desc');
                break;
            case 'status_asc' :
                $order = array('status', 'asc');
                break;
            case 'ct_asc' :
                $order = array('create_time', 'asc');
                break;
            default :
                $order = array('create_time', 'desc');
                break;
        }

        $MenuModel = model('Menu');

        $ret['menuList'] = $MenuModel->getList($title, $order, $page, $pageSize);
        $ret['amount'] = $MenuModel->listCount($title);
        $ret['page'] = $page;
        $ret['pageSize'] = $pageSize;

        format(0, 'success', $ret);
    }

    public function del()
    {
        $request = Request::instance();
        $id = $request->post('id');
        $id = intval($id);
        if ($id > 0) {
            $MenuModel = model('Menu');
            $result = $MenuModel->where('id',$id)->delete();
            if ($result) {
                format(0, '删除成功！');
            } else {
                format(-2, '删除失败，请稍后再试！');
            }
        } else {
            format(-2, '该菜单信息不存在！');
        }
    }

    public function bindMenuForRolePage()
    {
        $request = Request::instance();
        $id = $request->post('id');
        $id = intval($id);
        if ($id > 0) {
            $param = array(
                'role_id' => $id,
                'type'=>'menu'
            );
            $result = Auth::adminServiceRequest('config.getConfigListByRole', $param);
            if (!empty($result['data']['resCode']) && $result['data']['resCode'] == 2) {
                $configRoleList = $result['data']['data'];
                $MenuModel = model('Menu');
                $menuList = $MenuModel->where('status','=',1)->select();
                $roleConfigArr = array();
                if (!empty($configRoleList)) {
                    foreach ($configRoleList as $roleConfig) {
                        $roleConfigArr[$roleConfig['config_id']] = $roleConfig['role_id'];
                    }
                }
                foreach ($menuList as $index => $menu) {
                    if (!empty($roleConfigArr[$menu['id']])) {
                        $roleId =  intval($roleConfigArr[$menu['id']]);
                        $menuList[$index]['role_id'] = $roleId;
                    } else {
                        $user[$index]['role_id'] = 0;
                    }
                }
                $configRoleList = $menuList;
                $right = array();
                $left = array();
                if (!empty($configRoleList)) {
                    foreach ($configRoleList as $configRole) {
                        if (!empty($configRole['role_id']) && intval($configRole['role_id']) > 0) {
                            $roleId = intval($configRole['role_id']);
                            if ($roleId == $id) {
                                $right[] = $configRole['id'];
                            }
                        }
                        $left[] = array(
                            'key' => intval($configRole['id']),
                            'label' => $configRole['title']
                        );
                    }
                }
                $ret = array('left' => $left, 'right' => $right);
                format(0, 'success', $ret);
            }
            format(-2, '参数错误');
        } else {
            format(-2, 'fail');
        }
    }

    public function bindMenu()
    {
        $request = Request::instance();
        $id = $request->post('id');
        $act = $request->post('act',1);
        $menuIds = $request->post('ids');
        $id = intval($id);
        $menuIds = explode(',', $menuIds);
        if ($id <= 0 || empty($menuIds)) {
            format(-2, '参数错误');
        }

        foreach ($menuIds as $configId) {
            if (intval($configId) <= 0) {
                format(-2, '参数错误');
            }
        }

        $param = array(
            'role_id' => $id,
            'ids' => $menuIds,
            'type' => 'menu',
            'act'=>$act
        );

        $result = Auth::adminServiceRequest('config.bindConfig', $param);

        if (!empty($result['data']['resCode']) && $result['data']['resCode'] == 2) {
            format(0, 'success');
        }else{
            format(-2, '操作失败');
        }
    }

    public function getMenu(){

        if (Auth::isAdministrator()) {
            $parentMenu = $this->selectMenu(-888, array());
            format(0, 'success',$parentMenu);
        }

        $id = Session::get('role_id');
        $id = intval($id);
        if ($id <= 0) {
            format(-2, '不属于任何角色，暂无菜单');
        }

        $param = array(
            'role_id' => $id,
            'type'=>'menu'
        );
        $redis = Cache::store('redis');
        if($redis->get('menu_list_'.$id)){
            format(0,'success',$redis->get('menu_list_'.$id));
        }

        $result = Auth::adminServiceRequest('config.getConfigListByRole', $param);
        if (!empty($result['data']['resCode']) && $result['data']['resCode'] == 2) {
            $parentMenu = $this->selectMenu($id, $result['data']['data']);
            format(0, 'success',$parentMenu);
        }

        format(-2, $result['data']['msg']?$result['data']['msg']:$result['msg']);

    }

    private function selectMenu($roleId, $data)
    {
        $redis = Cache::store('redis');
        $configRoleList = $data;
        $parentMenu = array();
        $MenuModel = model('Menu');
        $order = array(
            'order' => 'desc'
        );

        if ($roleId == -888) {
            $menuList = $MenuModel->where('status', '=', 1)->order($order)->select();
        } elseif ($configRoleList) {
            $menuIds = array();
            foreach ($configRoleList as $value) {
                $menuIds[] = $value['config_id'];
            }
            $menuList = $MenuModel->where('status', '=', 1)->where('id', 'in', $menuIds)->order($order)->select();
        } else {
            return array();
        }
        foreach ($menuList as $key=>$value){
            if($value['pid'] == 0 || $value['pid'] == ''){
                $parentMenu[] = $value;
            }
        }
        foreach ($parentMenu as $key=>$value) {
            $temp_children = array();
            foreach ($menuList as $k => $item) {
                if ($item['pid'] == $value['id']){
                    $temp_children[] = $item;
                }
            }
            if(count($temp_children) > 0){
                $parentMenu[$key]['children'] = $temp_children;
            }
        }

        $redis->set('menu_list_'.$roleId,json_encode($parentMenu),1800);
        return $parentMenu;
    }

}